package com.masu.knows.portal.service.impl;

import com.masu.knows.portal.exception.ServiceException;
import com.masu.knows.portal.mapper.QuestionMapper;
import com.masu.knows.portal.mapper.UserMapper;
import com.masu.knows.portal.model.Answer;
import com.masu.knows.portal.mapper.AnswerMapper;
import com.masu.knows.portal.model.Question;
import com.masu.knows.portal.model.User;
import com.masu.knows.portal.service.IAnswerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.masu.knows.portal.vo.AnswerVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private AnswerMapper answerMapper;
    @Resource
    private QuestionMapper questionMapper;


    /**
     * 讲师回复问题 保存讲师回复的内容
     * @param answerVo
     * @param username
     * @return
     */
    @Override
    public Answer saveAnswer(AnswerVo answerVo, String username) {
        User user = userMapper.findUserByUsername(username);
        Answer answer=new Answer();
        answer.setContent(answerVo.getContent())
                .setLikeCount(0)
                .setUserId(user.getId())
                .setUserNickName(user.getNickname())
                .setQuestId(answerVo.getQuestionId())
                .setAcceptStatus(0);
        int row = answerMapper.insert(answer);

        if (row != 1){
            throw new ServiceException("新增数据异常");
        }

        return answer;
    }


    @Override
    public List<Answer> findAnswersAndComments(Integer qid) {
        return answerMapper.findAnswersAndCommentsByQid(qid);

    }

    @Override
    @Transactional
    public boolean accept(Integer answerId, String username) {
        Answer answer = answerMapper.selectById(answerId);

        // 已经被采纳 返回false
        if (Objects.equals(answer.getAcceptStatus(),1)){
            return false;
        }

        // 获取当前用户
        User user = userMapper.findUserByUsername(username);
        Question question = questionMapper.selectById(answer.getQuestId());

        // 学生采纳 当前用户的id和问题的发布者id必须保持一致
        if (Objects.equals(user.getId(),question.getUserId())){
            int num = answerMapper.updateAcceptStatus(answerId, 1);
            if (num != 1){
                throw new ServiceException("数据修改异常");
            }
            num = questionMapper.updateQuStatus(Question.SOLVED, question.getId());
            if (num != 1){
                throw new ServiceException("数据修改异常");
            }
            return true;
        }
        throw  new ServiceException("权限不足");
    }

}
